<?php

class IndexController extends Phalcon\Mvc\Controller
{
	// Display the "login" page
	public function indexAction() {
		// If login form was posted
		if ($this->request->isPost()) {
			$email = $this->request->getPost('email', 'email');
			$nick = $this->request->getPost('nick', 'string');

			$nick = strip_tags($nick);

			// Verify if the user is not already there.
			$new = false;
			$player = Players::findFirst(array('email'=>$email));
			if (!$player) {
				$new = true;
	            $player = new Players();
				$player->email = $email;
			}
			$player->nick = $nick;

			if ($player->save() == false) {
				foreach ($player->getMessages() as $message) {
					$this->flash->error((string) $message);
				}
			} else {
		        $this->session->set("player", $player->toArray());
				if($new) {
					$this->flash->success('Your profile information was created successfully');
				} else {
					$this->flash->success('Your profile information was updated successfully');
				}
			}
		}

		// If logged in (player is set) redirects to the game list
		if ($this->session->has("player")) {
			$this->response->redirect("games/list", true);
		}
	}
}
